﻿using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Web.Script.Serialization;
using System.Windows.Forms;

namespace AutoUpdate
{
    public class UpdateCheck
    {
        private JavaScriptSerializer convert = new JavaScriptSerializer();

        private string userName = ConfigurationManager.AppSettings["UserName"];
        private string password = ConfigurationManager.AppSettings["Password"];
        private string remoteConfigPath = ConfigurationManager.AppSettings["RemoteConfigPath"];
        private string ServiceType = ConfigurationManager.AppSettings["ServiceType"];

        private HttpClient client = new HttpClient();

        private string remoteFileName = "updateConfig.png";

        public UpdateCheck()
        {

        }

        /// <summary>
        /// 获得服务端的版本码
        /// </summary>
        /// <param name="configType">0:ftp;1:http</param>
        /// <returns></returns>
        public UpdateInfo GetUpdateInfo()
        {
            UpdateInfo updateInfo = null;

            #region 测试代码，用完删除
            //var json = File.ReadAllText("UpdateConfig.dat");
            //updateInfo = convert.Deserialize<UpdateInfo>(json);
            //return updateInfo;
            #endregion


            var url = string.Format("{0}/{1}", remoteConfigPath, remoteFileName);
            //ftp更新
            if (ServiceType == "1")
            {
                FtpWebRequest reqFTP;

                try
                {
                    reqFTP = (FtpWebRequest)WebRequest.Create(new Uri(url));
                    reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                    reqFTP.KeepAlive = false;
                    reqFTP.UseBinary = true;
                    reqFTP.UsePassive = true;
                    if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password))
                    {
                        reqFTP.Credentials = new NetworkCredential(userName, password);
                    }
                    FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                    Stream ftpStream = response.GetResponseStream();
                    StreamReader streamReader = new StreamReader(ftpStream, Encoding.UTF8);
                    string data = streamReader.ReadToEnd();
                    updateInfo = convert.Deserialize<UpdateInfo>(data);
                    streamReader.Close();
                    ftpStream.Close();
                    response.Close();
                }
                catch (Exception ex)
                {
                    MessageBoxEx.Show(ex.Message, "自动更新失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

            }
            else if (ServiceType == "2")
            {
                //http更新
                if (!string.IsNullOrEmpty(this.userName) && !string.IsNullOrEmpty(this.password))
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{this.userName}:{this.password}")));
                }

                Uri address = new Uri(url);
                var data = client.GetStringAsync(address).Result;//返回值
                updateInfo = convert.Deserialize<UpdateInfo>(data);
            }
            return updateInfo;
        }
    }
}